<script setup lang="ts">
import {cloneDeep, random} from "lodash";
import {MESSAGE_JSON} from "@/schema/interview";
import ChatBubble from "@/components/common/ChatBubble.vue";
import {storeToRefs} from "pinia";
import appStore from "@/store";
import {IMessage} from "@/interface/interviewInfo";
import {ElMessage} from "element-plus";
import {getAudio} from "@/http/m_api/ttsService";
import {AVMedia} from "vue-audio-visual";
import {
  Expand,
  VideoPause,
  VideoPlay,
  Fold,
  Close,
  Microphone,
  Refresh,
  Setting,
  List,
  ChatDotRound,
  EditPen,
} from "@element-plus/icons-vue";
import {ref, onMounted, onUnmounted, watch, nextTick, shallowRef, computed} from 'vue';
import {useSpeechRecognition} from '@vueuse/core';
import {getInterviewById, getInterviewMessages, receiveAIMessage, receiveAIMessageAgain} from "@/http/m_api/interview";
import {closeGlobalLoading, openGlobalLoading} from "@/utils/common";
import {gsvi_audio_path_pre} from "@/assets/ts/constant";

const status = ref(0);
const {PushMessage, ResetStore} = appStore.useInterviewJsonStore;
const {interviewNewStore} = storeToRefs(appStore.useInterviewJsonStore);

// Animation state
const fadeIn = ref(false);

onMounted(() => {
  setTimeout(() => {
    fadeIn.value = true;
  }, 100);
  PlayAudioQueue();
  audioRef.value.addEventListener('play', () => {
    paused.value = false;
  });
  audioRef.value.addEventListener('pause', () => {
    paused.value = true;
  });
  ProcessScroll(pastChatContainer);
});

// Theme and styling
const bubbleStyle = ref('light');
const bubbleStyleSelf = ref('default');
const customAiColor = ref(['#4f4f4f', '#ffffff']);
const customSelfColor = ref(['#95EC69', '#000000']);
const statusMessage = ['等待您的回答', 'AI思考中...', '正在提问'];
const statusColors = ['#67c23a', '#e6a23c', '#409eff'];

// Speech recognition
const speech = useSpeechRecognition({lang: shallowRef('zh-CN'), continuous: true});
const {isListening, isSupported, stop, result, isFinal} = speech;

watch(speech.result, () => {
  inputMsg.value = tempMsg.value + speech.result.value;
});
watch(speech.isListening, (newVal, oldVal) => {
  if (oldVal && audioInputting.value) {
    Record();
    ElMessage({type: 'warning', message: '长时间未识别到有效结果，已暂时结束录音'});
  }
});

// Refs
const audioRef = ref();
const microphoneRef = ref();
const chatContainer = ref();
const pastChatContainer = ref();

// State management
const drawer = ref(false);
const settingsDrawer = ref(false);
const inputMsg = ref('');
const audioInputting = ref(false);
const paused = ref(false);
const tempMsg = ref("");
const selection = ref<IMessage>();

// Message arrays
const pastMessages = ref<Array<IMessage>>([]);
const pastNewMessages = ref<Array<IMessage>>([]);
const newMessages = ref<Array<IMessage>>([]);

// Media streams
const currentMicrophoneStream = ref();

// Audio queue management
const AudioMessageQueue = ref<Array<IMessage>>([]);
const AudioReadyQueue = ref<Array<IReadyAudio>>([]);
const currentAudio = ref();
const playingAudio = ref(false);

interface IReadyAudio {
  audio_url: string;
  message: IMessage;
}

// Computed properties
const isRecording = computed(() => audioInputting.value || isListening.value);
const canSend = computed(() => status.value === 0 && inputMsg.value.trim() !== '');
const totalAudioItems = computed(() =>
    (currentAudio.value ? 1 : 0) + AudioReadyQueue.value.length + AudioMessageQueue.value.length
);
const hasSelection = computed(() => !!selection.value);

const getReferenceMessage = (id: number) => {
  if (id < interviewNewStore.value.Messages.length) {
    return interviewNewStore.value.Messages[id].content;
  } else {
    return '';
  }
};

const pushAudio = (message: IMessage) => {
  AudioMessageQueue.value.push(message);
  if (AudioMessageQueue.value.length === 1) {
    ProcessAudio();
  }
};

const pushMessages = (content: string) => {
  let message = cloneDeep(MESSAGE_JSON);
  message.id = interviewNewStore.value.Messages.length;
  message.type = false;
  message.content = content;
  message.hideContent = false;
  message.showAsMarkdown = true;
  message.audio_url = '';
  message.again = true
  if (selection.value) message.referenceId = selection.value.id;
  PushMessage(message);
  newMessages.value.push(message);

  nextTick(() => {
    ProcessScroll(chatContainer);
  });

  receiveMessages(content)
};

const currentMessageId = ref()

const handleStreamData = (chunk: string) => {
  const regex = /{.*?}/g;
  const matches = chunk.match(regex);
  if (matches) {
    matches.forEach((match) => {
      try {
        const obj = JSON.parse(match);
        if (obj.isFirst) {
          status.value = 2;
        }
        if (obj.content) {
          for (let i = 0; i < obj.content.length; i++) {
            newMessages.value[currentMessageId.value].content += obj.content[i];
          }
        }
      } catch (error) {
        console.error(`无法解析的 JSON: ${match}`);
      }
    });
  }
};

const receiveMessages = (content: string) => {
  let message = cloneDeep(MESSAGE_JSON);
  message.id = interviewNewStore.value.Messages.length;
  message.type = true;
  message.content = '';
  message.hideContent = false;
  message.showAsMarkdown = true;
  message.audio_url = '';
  PushMessage(message);
  currentMessageId.value = newMessages.value.length;
  newMessages.value.push(message);
  status.value = 1;
  receiveAIMessageAgain(
      {
        interviewId: interviewNewStore.value.id,
        content: content,
        hideContent: false,
        showAsMarkdown: true,
        referenceId: selection.value ? selection.value.id : null,
        audioUrl: '',
        again: true
      },
      handleStreamData,
      (error: any) => {
        ElMessage.error('出现错误，请重试');
        status.value = 0;
      },
      () => {
        status.value = 0;
      }
  );
};

// const loadInterview = async () => {
//   // TODO: Load interview data from backend
//   interviewNewStore.value.Settings.model_choice = 'universal';
//   interviewNewStore.value.Settings.universal_speaker_name = 'zh-CN-XiaoxiaoNeural';
//
//   for (let i = 0; i < 20; i++) {
//     if (i % 2 === 1) {
//       let message = cloneDeep(MESSAGE_JSON);
//       message.id = interviewNewStore.value.Messages.length;
//       message.type = false;
//       message.content = "这是用户的消息";
//       message.hideContent = false;
//       message.showAsMarkdown = true;
//       message.audio_url = '';
//       message.again = i > 15;
//       PushMessage(message);
//     } else {
//       let message = cloneDeep(MESSAGE_JSON);
//       message.id = interviewNewStore.value.Messages.length;
//       message.type = true;
//       message.content = `这是AI面试官的第${Math.floor(i/2) + 1}个问题，请仔细思考后回答。`;
//       message.hideContent = false;
//       message.showAsMarkdown = true;
//       message.audio_url = '';
//       message.again = i > 15;
//       PushMessage(message);
//     }
//   }
// };

const analyseMessages = () => {
  pastMessages.value = [];
  pastNewMessages.value = [];
  newMessages.value = [];

  for (let item of interviewNewStore.value.Messages) {
    if (item.again) {
      item.hideContent = !item.type;
      pastNewMessages.value.push(item);
    } else {
      item.hideContent = !item.type;
      pastMessages.value.push(item);
    }
  }
};

async function fetchAudio(message: IMessage): Promise<string> {
  try {
    if (message.audio_url && message.audio_url !== '') {
      return message.audio_url;
    }
    const data = await getAudio(message.content);

    if (!data) {
      ElMessage({type: "error", message: '数据异常！'});
      throw new Error('Invalid data received from getAudio');
    }

    let audioUrl;

    if (data instanceof ArrayBuffer) {
      const audioBlob = new Blob([data], {type: 'audio/mpeg'});
      audioUrl = URL.createObjectURL(audioBlob);
    } else if (data.audio_url) {
      audioUrl = data.audio_url.replace('http://127.0.0.1:9874', gsvi_audio_path_pre);
      message.audio_url = audioUrl;
    } else {
      ElMessage({type: "error", message: '音频数据格式不支持！'});
      throw new Error('Unsupported audio data format');
    }

    return audioUrl;
  } catch (error) {
    console.error('Error fetching audio:', error);
    ElMessage({type: "error", message: "合成失败，请稍后再试"});
    throw error;
  }
}

async function ProcessAudio() {
  while (AudioMessageQueue.value.length > 0) {
    let message = AudioMessageQueue.value[0];
    if (message) {
      try {
        const audioUrl = await fetchAudio(message);
        AudioReadyQueue.value.push({audio_url: audioUrl, message: message});
      } catch (error) {
        console.error('音频获取有误：', error);
      } finally {
        AudioMessageQueue.value.shift();
      }
    }
  }
}

async function PlayAudioQueue() {
  while (true) {
    if (AudioReadyQueue.value.length > 0) {
      if (playingAudio.value) {
        await new Promise<void>((resolve) => {
          const interval = setInterval(() => {
            if (!playingAudio.value || audioRef.value.readyState === 0 || audioRef.value?.ended) {
              currentAudio.value = null;
              clearInterval(interval);
              playingAudio.value = false;
              resolve();
            }
          }, 500);
        });
      } else {
        const item = AudioReadyQueue.value.shift()!;
        currentAudio.value = item;
        if (audioRef.value) {
          audioRef.value.src = item.audio_url;
          audioRef.value.play();
          playingAudio.value = true;
        } else {
          ElMessage({type: "error", message: '播放器出错！'});
          return;
        }
      }
    } else {
      if (audioRef.value?.ended) {
        currentAudio.value = null;
      }
      await new Promise<void>((resolve) => {
        setTimeout(() => {
          resolve();
        }, 500);
      });
    }
  }
}

const stopStream = (stream: MediaStream) => {
  if (stream) {
    const tracks = stream.getTracks();
    tracks.forEach((track: any) => {
      track.stop();
    });
  }
};

const Record = async () => {
  if (audioInputting.value) {
    audioInputting.value = false;
    if (currentMicrophoneStream.value) {
      stopStream(currentMicrophoneStream.value);
      currentMicrophoneStream.value = null;
    }
    speech.stop();
  } else {
    speech.result.value = '';
    tempMsg.value = inputMsg.value;
    speech.start();
    audioInputting.value = true;

    if (currentMicrophoneStream.value) {
      stopStream(currentMicrophoneStream.value);
    }
    currentMicrophoneStream.value = null;
    let option: any;
    if (interviewNewStore.value.Settings.microphoneChoice) {
      option = {deviceId: interviewNewStore.value.Settings.microphoneChoice.deviceId};
    } else {
      option = true;
    }
    await navigator.mediaDevices.getUserMedia({
      audio: option
    }).then((stream) => {
      currentMicrophoneStream.value = stream;
    }).catch((reason) => {
      ElMessage({type: "error", message: reason});
    });
  }
};

const send = () => {
  if (status.value !== 0) {
    ElMessage({type: "error", message: '当前无法发送，请等待面试官提问结束'});
    return;
  } else {
    if (inputMsg.value === '') {
      ElMessage({type: "error", message: '请输入内容'});
      return;
    }
    pushMessages(inputMsg.value);
    inputMsg.value = '';
  }
};

const selected = (id: number) => {
  if (selection.value && selection.value.id === id) {
    selection.value = undefined;
  } else {
    selection.value = interviewNewStore.value.Messages[id];
  }
};

const ProcessScroll = (container: any) => {
  if (container.value) {
    container.value.scrollTop = container.value.scrollHeight;
  }
};

const expandAll = (past: boolean) => {
  if (past) {
    for (let i = 0; i < pastMessages.value.length; i++) {
      pastMessages.value[i].hideContent = false;
    }
    for (let i = 0; i < pastNewMessages.value.length; i++) {
      pastNewMessages.value[i].hideContent = false;
    }
  } else {
    for (let i = 0; i < newMessages.value.length; i++) {
      newMessages.value[i].hideContent = false;
    }
  }
};

const foldAll = (past: boolean) => {
  if (past) {
    for (let i = 0; i < pastMessages.value.length; i++) {
      pastMessages.value[i].hideContent = true;
    }
    for (let i = 0; i < pastNewMessages.value.length; i++) {
      pastNewMessages.value[i].hideContent = true;
    }
  } else {
    for (let i = 0; i < newMessages.value.length; i++) {
      newMessages.value[i].hideContent = true;
    }
  }
};

const playAll = (past: boolean) => {
  if (past) {
    for (let item of pastMessages.value) {
      if (item.type) {
        pushAudio(item);
      }
    }
    for (let item of pastNewMessages.value) {
      if (item.type) {
        pushAudio(item);
      }
    }
  } else {
    for (let item of newMessages.value) {
      if (item.type) {
        pushAudio(item);
      }
    }
  }
};

const clearSelection = () => {
  selection.value = undefined;
};

const router = useRouter()

const loadInterview = async (id: number) => {
  openGlobalLoading()
  const data = await getInterviewById(id)
  if (data.code === 0) {
    interviewNewStore.value.id = data.data.id
    interviewNewStore.value.status = '进行中'
    interviewNewStore.value.startTime = new Date(data.data.startTime)
    interviewNewStore.value.Settings = data.data.settings
    console.log(interviewNewStore.value.Settings)
    const messages = await getInterviewMessages(interviewNewStore.value.id)
    interviewNewStore.value.Messages = messages.data.map((item: any) => {
          // 检查是否存在 audioUrl 属性
          if (item.audioUrl) {
            // 将 audioUrl 重命名为 audio_url
            item.audio_url = item.audioUrl;
            delete item.audioUrl; // 删除旧的 audioUrl 属性
          }
          return item;
        }
    )

    interviewNewStore.value.Messages.shift();
    analyseMessages()
  } else {
    ElMessage.error('面试记录不存在！')
    router.go(0)
  }
  closeGlobalLoading()

}

onUnmounted(() => {
  if (currentMicrophoneStream.value) {
    stopStream(currentMicrophoneStream.value);
  }
});
const route = useRoute();
ResetStore();
loadInterview(Number.parseInt(route.params.id as string));

const testAudio = require('@/assets/audio/testAudio.wav');
</script>

<template>
  <div class="interview-review-container" :class="{ 'fade-in': fadeIn }">
    <!-- Header -->
    <div class="review-header">
      <div class="header-content">
        <div class="header-left">
          <h2 class="section-title">
            <el-icon class="title-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chat-dots"
                   viewBox="0 0 16 16">
                <path
                    d="M5 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0m4 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0m3 1a1 1 0 1 0 0-2 1 1 0 0 0 0 2"/>
                <path
                    d="m2.165 15.803.02-.004c1.83-.363 2.948-.842 3.468-1.105A9 9 0 0 0 8 15c4.418 0 8-3.134 8-7s-3.582-7-8-7-8 3.134-8 7c0 1.76.743 3.37 1.97 4.6a10.4 10.4 0 0 1-.524 2.318l-.003.011a11 11 0 0 1-.244.637c-.079.186.074.394.273.362a22 22 0 0 0 .693-.125m.8-3.108a1 1 0 0 0-.287-.801C1.618 10.83 1 9.468 1 8c0-3.192 3.004-6 7-6s7 2.808 7 6-3.004 6-7 6a8 8 0 0 1-2.088-.272 1 1 0 0 0-.711.074c-.387.196-1.24.57-2.634.893a11 11 0 0 0 .398-2"/>
              </svg>
            </el-icon>
            面试复盘练习
          </h2>
          <p class="section-description">对比过往回答，提升面试表现</p>
        </div>
        <div class="audio-visualizer">
          <a-v-media
              ref="microphoneRef"
              type="frequ"
              frequ-direction="mo"
              :media="currentMicrophoneStream"
              class="visualizer-component"
          />
        </div>
        <div class="header-right">
          <div class="header-stats">
            <div class="stat-item">
              <span class="stat-label">历史消息</span>
              <span class="stat-value">{{ pastMessages.length + pastNewMessages.length }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">新回答</span>
              <span class="stat-value">{{ newMessages.length }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">音频队列</span>
              <span class="stat-value">{{ totalAudioItems }}</span>
            </div>
          </div>
          <el-button
              type="primary"
              circle
              @click="settingsDrawer = true"
              class="settings-toggle"
          >
            <el-icon>
              <Setting/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Past Interview Section -->
      <div class="past-section">
        <div class="section-header">
          <div class="section-title-wrapper">
            <el-icon class="section-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                   class="bi bi-clock-history" viewBox="0 0 16 16">
                <path
                    d="M8.515 1.019A7 7 0 0 0 8 1V0a8 8 0 0 1 .589.022zm2.004.45a7 7 0 0 0-.985-.299l.219-.976q.576.129 1.126.342zm1.37.71a7 7 0 0 0-.439-.27l.493-.87a8 8 0 0 1 .979.654l-.615.789a7 7 0 0 0-.418-.302zm1.834 1.79a7 7 0 0 0-.653-.796l.724-.69q.406.429.747.91zm.744 1.352a7 7 0 0 0-.214-.468l.893-.45a8 8 0 0 1 .45 1.088l-.95.313a7 7 0 0 0-.179-.483m.53 2.507a7 7 0 0 0-.1-1.025l.985-.17q.1.58.116 1.17zm-.131 1.538q.05-.254.081-.51l.993.123a8 8 0 0 1-.23 1.155l-.964-.267q.069-.247.12-.501m-.952 2.379q.276-.436.486-.908l.914.405q-.24.54-.555 1.038zm-.964 1.205q.183-.183.35-.378l.758.653a8 8 0 0 1-.401.432z"/>
                <path d="M8 1a7 7 0 1 0 4.95 11.95l.707.707A8.001 8.001 0 1 1 8 0z"/>
                <path
                    d="M7.5 3a.5.5 0 0 1 .5.5v5.21l3.248 1.856a.5.5 0 0 1-.496.868l-3.5-2A.5.5 0 0 1 7 9V3.5a.5.5 0 0 1 .5-.5"/>
              </svg>
            </el-icon>
            <h3 class="section-title">过往面试记录</h3>
          </div>
          <div class="section-controls">
            <el-tooltip content="折叠所有消息" placement="top">
              <el-button size="small" circle @click="foldAll(true)">
                <el-icon>
                  <Fold/>
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="展开所有消息" placement="top">
              <el-button size="small" circle @click="expandAll(true)">
                <el-icon>
                  <Expand/>
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="播放所有AI消息" placement="top">
              <el-button size="small" circle @click="playAll(true)">
                <el-icon>
                  <VideoPlay/>
                </el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>

        <div class="chat-container past-chat" ref="pastChatContainer">
          <div class="message-section">
            <div class="section-label">原始面试记录</div>
            <chat-bubble
                v-for="(msg, index) in pastMessages"
                :key="`past-${index}`"
                :message="msg"
                :bubble-style="bubbleStyle"
                :bubble-self-style="bubbleStyleSelf"
                :custom-ai-color="customAiColor"
                :custom-self-color="customSelfColor"
                :show-play="msg.type"
                :selected="selection && selection.id === msg.id"
                @play-audio="pushAudio(msg)"
                @select="selected(msg.id)"
                class="chat-message"
            >
              <template #reference v-if="msg.referenceId && msg.referenceId !== -1">
                {{ getReferenceMessage(msg.referenceId) }}
              </template>
            </chat-bubble>
          </div>

          <div v-if="pastNewMessages.length > 0" class="message-section">
            <el-divider class="section-divider">
              <span class="divider-text">往期旧问新答</span>
            </el-divider>
            <chat-bubble
                v-for="(msg, index) in pastNewMessages"
                :key="`past-new-${index}`"
                :message="msg"
                :bubble-style="bubbleStyle"
                :bubble-self-style="bubbleStyleSelf"
                :custom-ai-color="customAiColor"
                :custom-self-color="customSelfColor"
                :show-play="msg.type"
                :selected="selection && selection.id === msg.id"
                @play-audio="pushAudio(msg)"
                @select="selected(msg.id)"
                class="chat-message"
            >
              <template #reference v-if="msg.referenceId && msg.referenceId !== -1">
                {{ getReferenceMessage(msg.referenceId) }}
              </template>
            </chat-bubble>
          </div>
        </div>
      </div>

      <!-- New Practice Section -->
      <div class="practice-section">
        <div class="section-header">
          <div class="section-title-wrapper">
            <el-icon class="section-icon">
              <EditPen/>
            </el-icon>
            <h3 class="section-title">新回答练习</h3>
          </div>

          <div class="status-indicator">
            <div class="status-dot" :style="{ backgroundColor: statusColors[status] }"></div>
            <span class="status-text">{{ statusMessage[status] }}</span>
          </div>

          <div class="section-controls">
            <el-tooltip content="折叠所有消息" placement="top">
              <el-button size="small" circle @click="foldAll(false)">
                <el-icon>
                  <Fold/>
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="展开所有消息" placement="top">
              <el-button size="small" circle @click="expandAll(false)">
                <el-icon>
                  <Expand/>
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="播放所有AI消息" placement="top">
              <el-button size="small" circle @click="playAll(false)">
                <el-icon>
                  <VideoPlay/>
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="查看播放列表" placement="top">
              <el-button size="small" circle @click="drawer = true">
                <el-icon>
                  <List/>
                </el-icon>
                <el-badge v-if="totalAudioItems > 0" :value="totalAudioItems" class="audio-badge"/>
              </el-button>
            </el-tooltip>
          </div>
        </div>

        <div class="chat-container practice-chat" ref="chatContainer">
          <div v-if="newMessages.length === 0" class="empty-practice">
            <el-icon class="empty-icon">
              <EditPen/>
            </el-icon>
            <span class="empty-text">开始练习新的回答</span>
            <span class="empty-hint">选择左侧消息作为参考，然后输入您的新回答</span>
          </div>
          <chat-bubble
              v-for="(msg, index) in newMessages"
              :key="`new-${index}`"
              :message="msg"
              :bubble-style="bubbleStyle"
              :bubble-self-style="bubbleStyleSelf"
              :custom-ai-color="customAiColor"
              :custom-self-color="customSelfColor"
              :show-play="msg.type"
              @play-audio="pushAudio(msg)"
              class="chat-message"
          >
            <template #reference v-if="msg.referenceId && msg.referenceId !== -1">
              {{ getReferenceMessage(msg.referenceId) }}
            </template>
          </chat-bubble>
        </div>

        <!-- Input Section -->
        <div class="input-section">
          <!-- Reference Display -->
          <div v-if="hasSelection" class="reference-display">
            <div class="reference-header">
              <span class="reference-label">参考消息</span>
              <el-button size="small" text @click="clearSelection">
                <el-icon>
                  <Close/>
                </el-icon>
                清除选择
              </el-button>
            </div>
            <div class="reference-content">
              {{ selection.content }}
            </div>
          </div>

          <!-- Input Controls -->
          <div class="input-controls">
            <el-input
                type="textarea"
                v-model="inputMsg"
                placeholder="您可点选左侧消息，然后在此键入新的想法..."
                resize="none"
                :rows="4"
                :disabled="isListening || audioInputting"
                class="message-input"
                @keydown.ctrl.enter="send"
            />

            <div class="send-controls">
              <el-button
                  :type="isRecording ? 'danger' : 'success'"
                  @click="Record"
                  :disabled="!audioInputting && isListening"
                  class="record-btn"
              >
                <el-icon>
                  <Microphone v-if="!isRecording"/>
                  <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                       class="bi bi-mic-fill" viewBox="0 0 16 16">
                    <path d="M5 3a3 3 0 0 1 6 0v5a3 3 0 0 1-6 0z"/>
                    <path
                        d="M3.5 6.5A.5.5 0 0 1 4 7v1a4 4 0 0 0 8 0V7a.5.5 0 0 1 1 0v1a5 5 0 0 1-4.5 4.975V15h3a.5.5 0 0 1 0 1h-7a.5.5 0 0 1 0-1h3v-2.025A5 5 0 0 1 3 8V7a.5.5 0 0 1 .5-.5"/>
                  </svg>
                </el-icon>
                {{ isRecording ? '停止录音' : '开始录音' }}
              </el-button>
              <el-button
                  type="primary"
                  @click="send"
                  :disabled="!canSend"
                  class="send-btn"
              >
                <el-icon>
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-send"
                       viewBox="0 0 16 16">
                    <path
                        d="M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76z"/>
                  </svg>
                </el-icon>
                {{ status === 0 ? '发送回答' : '请等待...' }}
              </el-button>
            </div>
          </div>

          <!-- Audio Visualizer -->
        </div>
      </div>
    </div>

    <!-- Audio Player (Hidden) -->
    <audio ref="audioRef" :src="testAudio" style="display: none;"/>

    <!-- Playlist Drawer -->
    <el-drawer
        v-model="drawer"
        title="音频播放列表"
        direction="rtl"
        size="400px"
        class="playlist-drawer"
    >
      <div class="playlist-content">
        <div v-if="totalAudioItems === 0" class="empty-playlist">
          <el-icon class="empty-icon">
            <List/>
          </el-icon>
          <span>暂无播放项目</span>
        </div>

        <div v-else class="playlist-items">
          <!-- Currently Playing -->
          <div v-if="currentAudio" class="playlist-item current">
            <div class="item-header">
              <span class="item-index">正在播放</span>
              <div class="item-controls">
                <el-button
                    size="small"
                    :type="paused ? 'success' : 'warning'"
                    @click="paused ? audioRef.play() : audioRef.pause()"
                >
                  <el-icon>
                    <VideoPlay v-if="paused"/>
                    <VideoPause v-else/>
                  </el-icon>
                </el-button>
              </div>
            </div>
            <div class="item-content">
              {{ currentAudio.message.content }}
            </div>
            <div class="item-status playing">
              {{ paused ? '已暂停' : '正在播放' }}
            </div>
          </div>

          <!-- Ready Queue -->
          <div
              v-for="(item, index) in AudioReadyQueue"
              :key="`ready-${index}`"
              class="playlist-item ready"
          >
            <div class="item-header">
              <span class="item-index">{{ index + 1 + (currentAudio ? 1 : 0) }}</span>
              <div class="item-controls">
                <el-button
                    size="small"
                    type="danger"
                    @click="AudioReadyQueue.splice(index, 1)"
                >
                  <el-icon>
                    <Close/>
                  </el-icon>
                </el-button>
              </div>
            </div>
            <div class="item-content">
              {{ item.message.content }}
            </div>
            <div class="item-status ready">就绪</div>
          </div>

          <!-- Processing Queue -->
          <div
              v-for="(item, index) in AudioMessageQueue"
              :key="`processing-${index}`"
              class="playlist-item processing"
          >
            <div class="item-header">
              <span class="item-index">{{ index + 1 + (currentAudio ? 1 : 0) + AudioReadyQueue.length }}</span>
              <div class="item-controls">
                <el-button
                    size="small"
                    type="danger"
                    @click="AudioMessageQueue.splice(index, 1)"
                >
                  <el-icon>
                    <Close/>
                  </el-icon>
                </el-button>
              </div>
            </div>
            <div class="item-content">
              {{ item.content }}
            </div>
            <div class="item-status processing">处理中</div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- Settings Drawer -->
    <el-drawer
        v-model="settingsDrawer"
        title="界面设置"
        direction="rtl"
        size="350px"
        class="settings-drawer"
    >
      <div class="settings-content">
        <div class="setting-group">
          <h4 class="group-title">AI消息主题</h4>
          <el-select v-model="bubbleStyle" class="theme-select">
            <el-option label="浅色" value="light"/>
            <el-option label="深色" value="dark"/>
            <el-option label="自定义" value="custom"/>
          </el-select>
          <div v-if="bubbleStyle === 'custom'" class="color-pickers">
            <div class="color-item">
              <span>背景色</span>
              <el-color-picker v-model="customAiColor[0]" show-alpha/>
            </div>
            <div class="color-item">
              <span>文字色</span>
              <el-color-picker v-model="customAiColor[1]"/>
            </div>
          </div>
        </div>

        <div class="setting-group">
          <h4 class="group-title">我的消息主题</h4>
          <el-select v-model="bubbleStyleSelf" class="theme-select">
            <el-option label="默认" value="default"/>
            <el-option label="自定义" value="custom"/>
          </el-select>
          <div v-if="bubbleStyleSelf === 'custom'" class="color-pickers">
            <div class="color-item">
              <span>背景色</span>
              <el-color-picker v-model="customSelfColor[0]" show-alpha/>
            </div>
            <div class="color-item">
              <span>文字色</span>
              <el-color-picker v-model="customSelfColor[1]"/>
            </div>
          </div>
        </div>

        <div class="setting-group">
          <h4 class="group-title">音频控制</h4>
          <audio :src="testAudio" controls class="audio-player"/>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');

.interview-review-container {
  font-family: 'Noto Sans SC', sans-serif;
  height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  opacity: 0;
  transform: translateY(10px);
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);

  &.fade-in {
    opacity: 1;
    transform: translateY(0);
  }
}

.review-header {
  margin-bottom: 20px;
  padding: 20px 60px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      .section-title {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 24px;
        font-weight: 700;
        color: #2c3e50;
        margin: 0 0 8px;

        .title-icon {
          font-size: 28px;
          color: #409eff;
        }
      }

      .section-description {
        font-size: 16px;
        color: #64748b;
        margin: 0;
      }
    }

    .header-right {
      display: flex;
      justify-content: end;
      align-items: center;

      .header-stats {
        display: flex;
        gap: 24px;

        .stat-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 4px;

          .stat-label {
            font-size: 12px;
            color: #6b7280;
            font-weight: 500;
          }

          .stat-value {
            font-size: 20px;
            font-weight: 700;
            color: #374151;
          }
        }
      }

      .settings-toggle {
        margin-left: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        transition: all 0.3s ease;

        &:hover {
          transform: rotate(30deg);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
        }
      }
    }
  }
}

.main-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
}

.past-section {
  flex: 0 0 40%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    margin: 0;

    .section-title-wrapper {
      display: flex;
      align-items: center;
      gap: 8px;

      .section-icon {
        font-size: 20px;
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        margin: 0;
      }
    }

    .section-controls {
      display: flex;
      gap: 8px;

      .el-button {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
        }

        .audio-badge {
          position: absolute;
          top: -8px;
          right: -8px;
        }
      }
    }
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f8fafc;
    scroll-behavior: smooth;

    &.past-chat {
      background: linear-gradient(135deg, #fff9e6 0%, #fff3cd 100%);
    }

    &.practice-chat {
      background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
    }

    .message-section {
      margin-bottom: 20px;

      .section-label {
        font-size: 12px;
        font-weight: 600;
        color: #6b7280;
        margin-bottom: 12px;
        padding: 4px 8px;
        background: rgba(255, 255, 255, 0.8);
        border-radius: 4px;
        display: inline-block;
      }
    }

    .section-divider {
      margin: 24px 0;

      .divider-text {
        background: #f8fafc;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 600;
        color: #6b7280;
      }
    }

    .chat-message {
      margin-bottom: 16px;
      animation: slideIn 0.3s ease-out;
    }

    .empty-practice {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #9ca3af;
      text-align: center;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
      }

      .empty-text {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 8px;
      }

      .empty-hint {
        font-size: 14px;
        max-width: 300px;
        line-height: 1.5;
      }
    }
  }
}

.practice-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    margin: 0;

    .status-indicator {
      display: flex;
      align-items: center;
      gap: 10px;

      .status-dot {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        animation: pulse 2s infinite;
      }

      .status-text {
        font-weight: 600;
        font-size: 16px;
      }
    }

    .section-title-wrapper {
      display: flex;
      align-items: center;
      gap: 8px;

      .section-icon {
        font-size: 20px;
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        margin: 0;
      }
    }

    .section-controls {
      display: flex;
      gap: 8px;

      .el-button {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
        }

        .audio-badge {
          position: absolute;
          top: -8px;
          right: -8px;
        }
      }
    }
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f8fafc;
    scroll-behavior: smooth;

    &.past-chat {
      background: linear-gradient(135deg, #fff9e6 0%, #fff3cd 100%);
    }

    &.practice-chat {
      background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
    }

    .message-section {
      margin-bottom: 20px;

      .section-label {
        font-size: 12px;
        font-weight: 600;
        color: #6b7280;
        margin-bottom: 12px;
        padding: 4px 8px;
        background: rgba(255, 255, 255, 0.8);
        border-radius: 4px;
        display: inline-block;
      }
    }

    .section-divider {
      margin: 24px 0;

      .divider-text {
        background: #f8fafc;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 600;
        color: #6b7280;
      }
    }

    .chat-message {
      margin-bottom: 16px;
      animation: slideIn 0.3s ease-out;
    }

    .empty-practice {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #9ca3af;
      text-align: center;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
      }

      .empty-text {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 8px;
      }

      .empty-hint {
        font-size: 14px;
        max-width: 300px;
        line-height: 1.5;
      }
    }
  }

  .input-section {
    padding: 16px 20px;
    background: white;
    border-top: 1px solid #e5e7eb;

    .reference-display {
      margin-bottom: 16px;
      padding: 12px;
      background: #f0f9ff;
      border: 1px solid #bfdbfe;
      border-radius: 8px;

      .reference-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .reference-label {
          font-size: 12px;
          font-weight: 600;
          color: #1e40af;
        }
      }

      .reference-content {
        font-size: 14px;
        color: #374151;
        line-height: 1.5;
        max-height: 60px;
        overflow-y: auto;
      }
    }

    .input-controls {
      .input-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .input-title {
          font-size: 14px;
          font-weight: 600;
          color: #374151;
        }
      }

      .message-input {
        margin-bottom: 12px;

        :deep(.el-textarea__inner) {
          border-radius: 8px;
          border: 2px solid #e5e7eb;
          transition: all 0.3s ease;

          &:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
          }
        }
      }

      .send-controls {
        display: flex;
        justify-content: flex-end;

        .record-btn {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 8px 16px;
          font-weight: 500;
          border-radius: 6px;
          transition: all 0.3s ease;

          &:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }

        .send-btn {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 8px 16px;
          font-weight: 500;
          border-radius: 6px;
          transition: all 0.3s ease;

          &:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }

    .audio-visualizer {
      margin-top: 12px;
      height: 60px;
      border-radius: 8px;
      overflow: hidden;
      background: #1f2937;

      .visualizer-component {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.settings-toggle {
  margin-left: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;

  &:hover {
    transform: rotate(30deg);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
  }
}

.settings-drawer {
  :deep(.el-drawer__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    margin-bottom: 0;
    padding: 20px;
  }

  :deep(.el-drawer__body) {
    padding: 0;
  }
}

.settings-content {
  padding: 20px;

  .setting-group {
    margin-bottom: 24px;

    .group-title {
      font-size: 16px;
      font-weight: 600;
      color: #374151;
      margin: 0 0 12px;
    }

    .theme-select {
      width: 100%;
      margin-bottom: 12px;
    }

    .color-pickers {
      display: flex;
      flex-direction: column;
      gap: 8px;

      .color-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background: #f8fafc;
        border-radius: 6px;

        span {
          font-size: 14px;
          color: #6b7280;
        }
      }
    }

    .audio-player {
      width: 100%;
      border-radius: 6px;
    }
  }
}

.playlist-drawer {
  :deep(.el-drawer__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    margin-bottom: 0;
    padding: 20px;
  }

  :deep(.el-drawer__body) {
    padding: 0;
  }

  .playlist-content {
    .empty-playlist {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;
      color: #9ca3af;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 12px;
      }

      span {
        font-size: 16px;
      }
    }

    .playlist-items {
      padding: 20px;

      .playlist-item {
        background: white;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        border-left: 4px solid;

        &.current {
          border-left-color: #409eff;
          background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
        }

        &.ready {
          border-left-color: #67c23a;
        }

        &.processing {
          border-left-color: #e6a23c;
        }

        .item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .item-index {
            font-size: 12px;
            font-weight: 600;
            color: #6b7280;
          }
        }

        .item-content {
          font-size: 14px;
          color: #374151;
          line-height: 1.5;
          margin-bottom: 8px;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .item-status {
          font-size: 12px;
          font-weight: 500;
          padding: 2px 8px;
          border-radius: 4px;
          display: inline-block;

          &.playing {
            background: #e3f2fd;
            color: #1976d2;
          }

          &.ready {
            background: #e8f5e8;
            color: #2e7d32;
          }

          &.processing {
            background: #fff3e0;
            color: #f57c00;
          }
        }
      }
    }
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// Responsive Design
@media (max-width: 1400px) {
  .main-content {
    flex-direction: column;
    height: auto;
  }

  .past-section {
    flex: none;
    height: 400px;
  }

  .practice-section {
    flex: 1;
    min-height: 500px;
  }
}

@media (max-width: 768px) {
  .interview-review-container {
    padding: 10px;
  }

  .review-header {
    .header-content {
      flex-direction: column;
      gap: 16px;
      text-align: center;
    }
  }

  .main-content {
    gap: 10px;
  }

  .past-section,
  .practice-section {
    .section-header {
      .section-controls {
        flex-wrap: wrap;
        gap: 4px;
      }
    }
  }
}
</style>
